﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace WebApp
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class test
    {
       
        /// <summary>
        /// 利用系统自动封装成json格式
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        public List<SliverlightApp.Person> GetPersonList()
        {
            List<SliverlightApp.Person> lst = new List<SliverlightApp.Person>();
            lst.Add(new SliverlightApp.Person() { Name = "菩提树下的杨过", Age = 30 });
            lst.Add(new SliverlightApp.Person() { Name = "小龙女", Age = 100 });
            return lst;
        }

        /// <summary>
        /// 自己封装成json格式
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(Method = "GET")]
        public Stream GetPersonList2()
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("Name", typeof(string));
            tbl.Columns.Add("Age", typeof(System.Int32));
            tbl.Rows.Add("菩提树下的杨过", 30);
            tbl.Rows.Add("小龙女", 100);
            return GetStream(CreateJsonParameters(tbl));
        }


        /// <summary>
        /// 将datatable转化成json字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private string CreateJsonParameters(DataTable dt)
        {            
            StringBuilder JsonString = new StringBuilder();                   
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"Head\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString().Replace("\"", "\\\"") + "\":" + "\"" + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString().Replace("\"", "\\\"") + "\":" + "\"" + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
                        }
                    }
                   
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 辅助方法，用于输出流
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private Stream GetStream(string str)
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.AutoFlush = true;
            sw.Write(str);
            ms.Position = 0;
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
            return ms;
        }
    }
}
